package srx.open.com.activity;

import android.app.Activity;
import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.DialogInterface.OnClickListener;
import android.content.Intent;
import android.content.res.Resources;
import android.net.Uri;
import android.os.Bundle;
import android.support.v4.app.FragmentActivity;
import android.view.View;
import android.view.WindowManager;
import android.view.inputmethod.InputMethodManager;

import java.util.List;

import cn.bmob.v3.BmobQuery;
import cn.bmob.v3.BmobSMS;
import cn.bmob.v3.exception.BmobException;
import cn.bmob.v3.listener.BmobUpdateListener;
import cn.bmob.v3.listener.FindListener;
import cn.bmob.v3.listener.RequestSMSCodeListener;
import cn.bmob.v3.listener.SaveListener;
import cn.bmob.v3.update.BmobUpdateAgent;
import cn.bmob.v3.update.UpdateResponse;
import cn.bmob.v3.update.UpdateStatus;
import srx.open.com.bean.SrxApplication;
import srx.open.com.bean.User;
import srx.open.com.utils.BaiDuLbsHelper;
import srx.open.com.utils.DataBaseHelper;
import srx.open.com.utils.Log;
import srx.open.com.utils.OpenToast;
import srx.open.com.widgets.AppUpdateDialogWindow;

/**
 * 扩展基类.
 *
 * @author hailongqiu 356752238@qq.com
 */
public class ExtendBaseActivity extends FragmentActivity {
    private static final String TAG = "ExtendBaseActivity";

    public Context mContext;
    public Resources mResource;
    private AppUpdateDialogWindow mAppUpdateDialogWindow;
    public DataBaseHelper mDataBaseHelper; // 数据库操作.
    public BaiDuLbsHelper mBaiDuLbsHelper; // 百度定位.
    public SrxApplication mSrxApplication;

    public String phoneStr = "";

    public void initAllDatas() {

    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        mContext = getApplicationContext();
        mResource = mContext.getResources();
        /* */
        mSrxApplication = (SrxApplication) getApplication();
        /* 获取 数据库 DataBaseHelper */
        mDataBaseHelper = mSrxApplication.mDataBaseHelper;
        /* 获取百度定位变量 */
        mBaiDuLbsHelper = mSrxApplication.mBaiDuLbsHelper;
        initAllDatas();
        initAllViews();
    }

    public void initAllViews() {

    }

    /**
     * 隐藏软键盘
     */
    public void hideSoftInputView() {
        InputMethodManager manager = ((InputMethodManager) this.getSystemService(Activity.INPUT_METHOD_SERVICE));
        if (getWindow().getAttributes().softInputMode != WindowManager.LayoutParams.SOFT_INPUT_STATE_HIDDEN) {
            if (getCurrentFocus() != null)
                manager.hideSoftInputFromWindow(getCurrentFocus().getWindowToken(), InputMethodManager.HIDE_NOT_ALWAYS);
        }
    }

    // 显示软键盘
    public void showSoftInputView(View v) {
        if (getWindow().getAttributes().softInputMode == WindowManager.LayoutParams.SOFT_INPUT_STATE_HIDDEN) {
            if (getCurrentFocus() != null)
                ((InputMethodManager) getSystemService(INPUT_METHOD_SERVICE))
                        .showSoftInput(v, 0);
        }
    }

    /**
     * 调用手机拨号键盘.
     *
     * @param phoneNumber 手机号码.
     */
    public void callPhoneNumberKeyboard(String phoneNumber) {
        Intent intent = new Intent(Intent.ACTION_DIAL, Uri.parse("tel:" + phoneNumber));
        intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        startActivity(intent);
    }

    /**
     * 发送短信
     * @param phoneStr 手机号码
     * @param smsBody 短信内容
     */
    public void sendSMS(String phoneStr, String smsBody) {
        Uri smsToUri = Uri.parse("smsto:" + phoneStr);
        Intent intent = new Intent(Intent.ACTION_SENDTO, smsToUri);
        intent.putExtra("sms_body", smsBody);
        startActivity(intent);
    }

    public void openActivity(Class<?> cls) {
        Intent intents = new Intent(mContext, cls);
        startActivity(intents);
    }

    /**
     * 检验APP是否需要更新.
     */
    public void checkAppUpload() {
//        BmobUpdateAgent.initAppVersion(this);
        BmobUpdateAgent.setUpdateOnlyWifi(false);
        BmobUpdateAgent.setUpdateListener(new BmobUpdateListener() {
            @Override
            public void onUpdateReturned(int updateStatus, UpdateResponse updateInfo) {
                if (updateStatus == UpdateStatus.Yes) {//版本有更新
                    Log.d(TAG, "UpdateResponse:" + updateInfo.toString());
                } else if (updateStatus == UpdateStatus.No) {
                    OpenToast.showMsg("已经是最新版本");
                } else if (updateStatus == UpdateStatus.EmptyField) {//此提示只是提醒开发者关注那些必填项，测试成功后，无需对用户提示
                    OpenToast.showMsg("请检查你AppVersion表的必填项，1、target_size（文件大小）是否填写；2、path或者android_url两者必填其中一项。");
                } else if (updateStatus == UpdateStatus.IGNORED) {
                    OpenToast.showMsg("该版本已被忽略更新");
                } else if (updateStatus == UpdateStatus.ErrorSizeFormat) {
                    OpenToast.showMsg("请检查target_size填写的格式，请使用file.length()方法获取apk大小。");
                } else if (updateStatus == UpdateStatus.TimeOut) {
                    OpenToast.showMsg("查询出错或查询超时");
                }
            }
        });
        BmobUpdateAgent.forceUpdate(this);
//        BmobUpdateAgent.update(this);
    }

    /**
     * 检查用户号码是否已被注册.
     */
    public void checkUserName(final String userName, final String title,
                              final String msg, final String posBtnStr) {
        BmobQuery<User> query = new BmobQuery<User>();
        query.addWhereEqualTo("username", userName);
        query.findObjects(getApplicationContext(), new FindListener<User>() {
            @Override
            public void onSuccess(List<User> userList) {
                if (userList.size() > 0) {
                    AlertDialog.Builder builder = new AlertDialog.Builder(
                            ExtendBaseActivity.this);
                    builder.setTitle(title);
                    builder.setMessage(msg);
                    builder.setPositiveButton(posBtnStr, new OnClickListener() {
                        @Override
                        public void onClick(DialogInterface dialog, int which) {
                            // 发送验证码
                            BmobSMS.requestSMSCode(mContext, phoneStr, "forgetPass", new RequestSMSCodeListener() {
                                @Override
                                public void done(Integer integer, BmobException ex) {
                                    if (ex == null) {
                                        OpenToast.showMsg("验证码已发送");
                                    } else {
                                        OpenToast.showMsg("验证码发送失败");
                                    }
                                }
                            });
                            // 进入快捷注册并登陆界面.
                            Intent intents = new Intent(
                                    getApplicationContext(),
                                    NoAccountShortcutLoginActivity.class);
                            intents.putExtra("username", "" + userName);
                            startActivity(intents);
                            finish();
                        }
                    });
                    builder.setNegativeButton("取消", new OnClickListener() {
                        @Override
                        public void onClick(DialogInterface dialog, int which) {
                            dialog.dismiss();
                        }
                    });
                    builder.create();
                    builder.show();
                } else { // 如果当前账号没有被注册.
                    onCheckUserNoexist();
                }
            }

            @Override
            public void onError(int code, String msg) {
                OpenToast.showMsg(msg + " " + code);
            }
        });
    }

    public void onCheckUserNoexist() {

    }

    // /////// 登陆接口. //////////////////

    public void login(final String name, final String pass) {
        User mUser;
        mUser = new User();
        mUser.setUsername(name);
        mUser.setPassword(pass);
        mUser.login(mContext, new SaveListener() {

            @Override
            public void onSuccess() {
                Log.d("登录成功");
                onLoginSuccess();
            }

            @Override
            public void onFailure(int code, String msg) {
                Log.d("登录失败:" + msg);
                switch (code) {
                    case 101:
                        msg = "账号或者密码错误";
                        break;
                    default:
                        break;
                }
                onLoginFailure(code, msg);
            }
        });
    }

    public void onLoginSuccess() {

    }

    public void onLoginFailure(int code, String msg) {
    }

    // //////// 注册接口 ///////////

    /**
     * 注册账号.
     */
    public void register(final String username, final String pass) {
        final User user = new User();
        user.setUsername(username);
        user.setPassword(pass);
        user.setMobilePhoneNumber("" + username);
        user.setMobilePhoneNumberVerified(true);
        user.signUp(getApplicationContext(), new SaveListener() {
            @Override
            public void onSuccess() {
                onRegisterSuccess(user);
            }

            @Override
            public void onFailure(int code, String msg) {
                switch (code) {
                    case 202:
                        msg = "手机号已被注册";
                        break;
                    default:
                        break;
                }
                onRegisterFailure(code, msg);
            }
        });
    }

    public void onRegisterSuccess(User user) {

    }

    public void onRegisterFailure(int code, String msg) {

    }

}
